import SparkMD5 from 'spark-md5';
import { getApiToken, getViewerApiToken } from '@/http/api'
import pinia from '@/store/index'
import { useMainStore } from '@/store/config'
const $store = useMainStore(pinia)

// 获取签名
const getSign = (appSecret, params) => {
    const paramString = _sortParams(params);
    const signString = appSecret + paramString + appSecret;
    return SparkMD5.hash(signString).toUpperCase();
};
function _sortParams(params) {
    const keys = Object.keys(params).sort();
    let paramsString = '';
    for (let i = 0; i < keys.length; i++) {
      paramsString += keys[i] + params[keys[i]];
    }
    return paramsString;
}

// 获取聊天室信息
const getChatInfo = async () => {
  const apiTokenParams = {
    appId: $store.appId,
    channelId: $store.channelId,
    role: $store.role,
    timestamp: $store.timestamp,
    userId: $store.userId,
  };

  // ！！！不要在前端生成sign，此处仅供参考
  apiTokenParams.sign = getSign(
    $store.appSecret,
    apiTokenParams
  );
  
  return await getApiToken(apiTokenParams)
}

const myViewerApiTokenGetter = async () => {
  const apiTokenParams = {
    appId: $store.appId,
    channelId: $store.channelId,
    timestamp: $store.timestamp,
    viewerId: $store.userId,
  };

  // ！！！不要在前端生成sign，此处仅供参考
  apiTokenParams.sign = getSign(
    $store.appSecret,
    apiTokenParams
  );
  return await getViewerApiToken(apiTokenParams)
}

export default {
	getSign,
  getChatInfo,
  myViewerApiTokenGetter,
};
